<template>
  <view class="content">
    <view class="page">
      <view
        class="page-content"
        v-for="(item, index) in avatar_arr"
        :key="index"
        @click="previewImg(index)"
      >
        <image :src="item.imageUrl" mode="aspectFill" />
      </view>
    </view>
    <u-loadmore
      :status="status"
      :loading-text="loadingText"
      :loadmore-text="loadmoreText"
      :nomore-text="nomoreText"
    />
    <TopButton v-if="isShowTop"></TopButton>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad, onReachBottom, onPageScroll } from '@dcloudio/uni-app'
import { userApi } from '@/request/api.js'
import TopButton from '@/components/TopButton.vue'
import { useCounterStore } from '@/store/counter.js'
const store = useCounterStore()

// 创建响应式数据
const isShowTop = ref(false)
const status = ref('loadmore')
const loadingText = ref('努力加载中')
const loadmoreText = ref('轻轻上拉')
const nomoreText = ref('我也是有底线的~')
const avatar_arr = ref([])
// 请求参数
const params = ref({
  page: 1,
  pageSize: 10,
  imageType: null
})
const total = ref(0) //总条数
onLoad((option) => {
  store.showLoading = true
  params.value.imageType = option.type
  setTimeout(() => {
    getAvatar()
  }, 100)
})
onMounted(() => {})
// 获取头像函数Api接口
async function getAvatar() {
  let res = await userApi.getNetPhoto(params.value)
  if (avatar_arr.value.length > 0) {
    avatar_arr.value = [...avatar_arr.value, ...res.data.records]
  } else {
    avatar_arr.value = res.data.records
  }
  total.value = res.data.total
  store.showLoading = false
}
// 预览图片
function previewImg(index) {
  const imgeList = avatar_arr.value.map((item, i) => {
    return item.imageUrl
  })
  uni.previewImage({
    urls: imgeList,
    current: avatar_arr.value[index].imageUrl
  })
}
// 上拉加载更多
onReachBottom(() => {
  if (avatar_arr.value.length >= total.value) {
    status.value = 'nomore'
  } else {
    params.value.page += 1
    setTimeout(() => {
      status.value = 'loading'
      getAvatar()
    }, 1000)
  }
})
// 监听页面·滚动
onPageScroll((e) => {
  if (e.scrollTop >= 200) {
    isShowTop.value = true
  } else if (e.scrollTop === 0) {
    isShowTop.value = false
  }
})
</script>

<style lang="scss" scoped>
.content {
  padding-bottom: 20px;
  .page {
    width: 100%;
    height: 100%;
    padding: 20rpx 20rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    box-sizing: border-box;
    .page-content {
      width: 48%;
      height: 320rpx;
      margin-bottom: 20rpx;
      image {
        width: 100%;
        height: 100%;
        border-radius: 16rpx;
      }
    }
  }
}
</style>
